package com.yoda.mall.admin.auth;

import com.yoda.common.Status;
import com.yoda.common.constant.RC;
import com.yoda.common.exception.BusinessException;
import com.yoda.common.exception.ErrorResult;
import com.yoda.mall.admin.intercepter.ThreadContext;
import com.yoda.mall.model.entity.ums.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Configuration
public class AdminInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 配置拦截器,验证请求token,判定是否合法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        log.info("接收到请求:{}",uri);
        //获取token
        String info = request.getHeader("info");

        int index = 0;
        for (int i = 0; i < info.length(); i++) {
            if (info.charAt(i)==','){
                index=i;
                break;
            }
        }
        long id = Long.parseLong(info.substring(0, index));
        String username = info.substring(index+1);

        //判断redis黑名单,剔除登录
        String blackIdKey = RC.BLACK_LIST_ID;

        boolean res = Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(blackIdKey, id));
        if (res){
            //用户已被删除
            throw new BusinessException(ErrorResult.builder().errMessage("用户已被禁用").errCode(Status.FORBIDDEN.getCode()).build());
        }
        //存入用户id存入线程变量副本
        Admin admin = new Admin();
        admin.setId(id);
        admin.setUsername(username);
        ThreadContext.setAdmin(admin);
        return true;
    }

    /**
     * 拦截完成后执行清空副本方法
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @param ex       前女友
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空副本
        ThreadContext.clear();
    }
}
